package com.LachesismStorm.lachesism.member.websocket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.LachesismStorm.lachesism.core.util.AsyncUtil;
import com.LachesismStorm.lachesism.core.util.LachesismTools;
import com.LachesismStorm.lachesism.member.service.DatingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@ServerEndpoint(value = "/chat")
@Component
public class WebSocketService {

    @Resource
    private DatingService datingService;

    // 用于保存 WebSocket 连接对象
    public static ConcurrentHashMap<Integer, Session> sessionMap = new ConcurrentHashMap<>();

    // 脏话列表


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("加入了一个新 session");
        Map<String, Object> userProperties = session.getUserProperties();
        int size = sessionMap.size();
        userProperties.put("index", size);
        sessionMap.put(size, session);
        sendMessage("ok", session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) throws IOException {
        Map<String, Object> userProperties = session.getUserProperties();
        Integer index = (Integer) userProperties.get("index");
        sessionMap.remove(index);
    }

    /**
     * 接收消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        if ("ping".equals(message)) {
            sendMessage("pong", session);
            return;
        }
        // 把字符串转换成 JSON
        JSONObject json = JSONUtil.parseObj(message);
        Integer userId = json.getInt("id");
        Map<String, Object> userProperties = session.getUserProperties();
        userProperties.put(String.valueOf(userId), userId);
        Integer index = (Integer) userProperties.get("index");
        sessionMap.put(index, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket error with session: {}", session, error);
        sessionMap.values().remove(session);  // 移除发生错误的 session
    }

    /**
     * 通知
     */
    public static void notification(Integer userId) {
        for (Map.Entry<Integer, Session> entry : sessionMap.entrySet()) {
            Session session = entry.getValue();
            if (session.getUserProperties().containsKey(userId.toString())) {
                sendOk(session);
            }
        }

    }

    /**
     * 广播
     */
    public static void broadcast(String message) {
        for (Session session : sessionMap.values()) {
            session.getAsyncRemote().sendText(message);
        }
    }

    /**
     * 封装发送消息给客户端
     */
    private void sendMessage(String message, Session session) {
//        message = replaceSwearWords(message);
        session.getAsyncRemote().sendText(message);
    }

    private static void sendOk(Session session) {
//        message = replaceSwearWords(message);
        session.getAsyncRemote().sendText("message");
    }

}